﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Pipra.Math;
using Pipra.Math.Geometry;
using Pipra.Uom;
using Pipra.Uom.Core;

namespace Pipra.Gis.Ogc
{
    /// <summary>
    /// Parses WKT text to entities.
    /// </summary>
    public class WktParser {

        private class WktReader : IEnumerator<char> {
            private TextReader _reader;

            public WktReader(TextReader reader, CultureInfo culture) {
                _reader = reader;
                Culture = culture;
            }

            private CultureInfo Culture { get; set; }

            public char Current { get; private set; }

            public char CurrentUpper { get { return Char.ToUpperInvariant(Current); } }

            public void Dispose() {
                _reader = null;
            }

            object System.Collections.IEnumerator.Current {
                get { return Current; }
            }

            public bool MoveNext() {
                int iChar = _reader.Read();
                if (iChar >= 0) {
                    Current = (char)iChar;
                    return true;
                }
                Current = '\0';
                return false;
            }

            public void Reset() {
                throw new NotSupportedException();
            }

            public bool SkipWhiteSpace() {
                bool ok = true;
                while (IsWhiteSpace && ok) {
                    ok = MoveNext();
                }
                return ok;
            }

            public bool IsWhiteSpace {
                get { return Char.IsWhiteSpace(Current); }
            }

            public bool IsDigit {
                get { return Char.IsDigit(Current); }
            }

            public bool IsDoubleQuote {
                get { return '\"' == Current; }
            }

            public bool IsLetter {
                get { return Char.IsLetter(Current); }
            }

            public bool IsComma {
                get { return ',' == Current; }
            }

            public bool IsOpenBracket {
                get { return '[' == Current || '(' == Current; }
            }

            public bool IsCloseBracket {
                get { return ']' == Current || ')' == Current; }
            }

            public bool IsValidForDouble {
                get {
                    return !IsWhiteSpace
                        && !IsComma
                        && (
                            IsDigit
                            || '+' == Current
                            || '-' == Current
                            || 'e' == Current
                            || 'E' == Current
                            || '.' == Current
                            || ',' == Current
                            || Culture.NumberFormat.PositiveSign.IndexOf(Current) >= 0
                            || Culture.NumberFormat.NegativeSign.IndexOf(Current) >= 0
                            || Culture.NumberFormat.NumberDecimalSeparator.IndexOf(Current) >= 0
                            || Culture.NumberFormat.NumberGroupSeparator.IndexOf(Current) >= 0
                        )
                    ;
                }
            }

            public bool IsKeyword {
                get { return IsLetter || '_' == Current; }
            }

        }

        private readonly AuthorityFactoryManager _authFacs;
        private readonly CultureInfo _culture;
        private readonly UomGraph _uomGraph;

        /// <summary>
        /// Constructs a WKT parser with the given <paramref name="options"/>.
        /// </summary>
        /// <param name="options">The WKT options.</param>
        public WktParser(WktOptions options) : this(options, null, null) { }

        /// <summary>
        /// constructs a WKT parser with the given <paramref name="options"/> and authority factory.
        /// </summary>
        /// <param name="options">The WKT options.</param>
        /// <param name="authFacs">THe authority factory to construct entities.</param>
        public WktParser(WktOptions options, AuthorityFactoryManager authFacs, UomGraph uomGraph) {
            Options = options;
            _authFacs = authFacs ?? AuthorityFactoryManager.Default;
            _culture = CultureInfo.CurrentCulture;
            _uomGraph = uomGraph ?? new CoreUomGraph();
        }

        /// <summary>
        /// The WKT options.
        /// </summary>
        public WktOptions Options { get; private set; }

        private double ReadDouble(WktReader reader) {
            var sb = new StringBuilder();
            while (reader.IsValidForDouble) {
                sb.Append(reader.Current);
                if (!reader.MoveNext()) {
                    break;
                }
            }
            double d;
            return Double.TryParse(sb.ToString(), out d) ? d : Double.NaN;
        }

        private string ReadQuotedString(WktReader reader) {
            bool readOk = true;
            var sb = new StringBuilder();
            if (reader.IsDoubleQuote) {
                if (!(readOk = reader.MoveNext())) {
                    return null;
                }
            }
            while (!reader.IsDoubleQuote) {
                sb.Append(reader.Current);
                if (!(readOk = reader.MoveNext())) {
                    break;
                }
            }
            if (readOk) {
                reader.MoveNext();
            }
            return sb.ToString();
        }

        private WktKeyword ReadKeywordSubmatch(string submatch, WktKeyword keyword, WktReader reader) {
            return ReadKeywordSubmatch(submatch, reader) ? keyword : WktKeyword.None;
        }

        private bool ReadKeywordSubmatch(string submatch, WktReader reader) {
            for (var i = 0; i < submatch.Length; i++) {
                if (
                    (reader.CurrentUpper != submatch[i])
                    ||
                    (!reader.MoveNext() && submatch.Length != (i + 1))
                ) {
                    return false;
                }
            }
            return true;
        }

        private WktKeyword ReadKeyword(WktReader reader) {
            char preChar = reader.CurrentUpper;
            if (!reader.MoveNext()) {
                return WktKeyword.None;
            }
            switch (preChar) {
            case 'A': {
                    preChar = reader.CurrentUpper;
                    if (reader.MoveNext()) {
                        switch (preChar) {
                        case 'U':
                            return ReadKeywordSubmatch("THORITY", WktKeyword.Authority, reader);
                        case 'X':
                            return ReadKeywordSubmatch("IS", WktKeyword.Axis, reader);
                        }
                    }
                    break;
                }
            case 'C': {
                    if (ReadKeywordSubmatch("O", reader)) {
                        preChar = reader.CurrentUpper;
                        if (reader.MoveNext()) {
                            switch (preChar) {
                            case 'M':
                                return ReadKeywordSubmatch("PD_CS", WktKeyword.CompoundCs, reader);
                            case 'N':
                                return ReadKeywordSubmatch("CAT_MT", WktKeyword.ConcatMt, reader);
                            }
                        }
                    }
                    break;
                }
            case 'D':
                return ReadKeywordSubmatch("ATUM", WktKeyword.Datum, reader);
            case 'F':
                return ReadKeywordSubmatch("ITTED_CS", WktKeyword.FittedCs, reader);
            case 'G': {
                    if (ReadKeywordSubmatch("EO", reader)) {
                        preChar = reader.CurrentUpper;
                        if (reader.MoveNext()) {
                            WktKeyword temp;
                            switch (preChar) {
                            case 'C': {
                                    temp = WktKeyword.GeocentricCs;
                                    break;
                                }
                            case 'G': {
                                    temp = WktKeyword.GeographicCs;
                                    break;
                                }
                            default:
                                return WktKeyword.None;
                            }
                            return ReadKeywordSubmatch("CS", reader) ? temp : WktKeyword.None;
                        }
                    }
                    break;
                }
            case 'I':
                return ReadKeywordSubmatch("NVERSE_MT", WktKeyword.InverseMt, reader);
            case 'L': {
                    if (ReadKeywordSubmatch("OCAL_", reader)) {
                        preChar = reader.CurrentUpper;
                        if (reader.MoveNext()) {
                            switch (preChar) {
                            case 'C':
                                return ReadKeywordSubmatch("S", WktKeyword.LocalCs, reader);
                            case 'D':
                                return ReadKeywordSubmatch("ATUM", WktKeyword.LocalDatum, reader);
                            }
                        }
                    }
                    break;
                }
            case 'P': {
                    preChar = reader.CurrentUpper;
                    if (reader.MoveNext()) {
                        switch (preChar) {
                        case 'A': {
                                preChar = reader.CurrentUpper;
                                if (reader.MoveNext()) {
                                    switch (preChar) {
                                    case 'S':
                                        return ReadKeywordSubmatch("STHROUGH_MT", WktKeyword.PassthroughMt, reader);
                                    case 'R': {
                                            if (ReadKeywordSubmatch("AM", reader)) {
                                                preChar = reader.CurrentUpper;
                                                if (reader.MoveNext()) {
                                                    switch (preChar) {
                                                    case 'E':
                                                        return ReadKeywordSubmatch("TER", WktKeyword.Parameter,
                                                                                   reader);
                                                    case '_':
                                                        return ReadKeywordSubmatch("MT", WktKeyword.ParamMt, reader);
                                                    }
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                                break;
                            }
                        case 'R': {
                                preChar = reader.CurrentUpper;
                                if (reader.MoveNext()) {
                                    switch (preChar) {
                                    case 'I':
                                        return ReadKeywordSubmatch("MEM", WktKeyword.PrimeMeridian, reader);
                                    case 'O': {
                                            if (ReadKeywordSubmatch("J", reader)) {
                                                preChar = reader.CurrentUpper;
                                                if (reader.MoveNext()) {
                                                    switch (preChar) {
                                                    case 'C':
                                                        return ReadKeywordSubmatch("S", WktKeyword.ProjectedCs,
                                                                                   reader);
                                                    case 'E':
                                                        return ReadKeywordSubmatch("CTION", WktKeyword.Projection,
                                                                                   reader);
                                                    }
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }
                    break;
                }
            case 'S':
                return ReadKeywordSubmatch("PHEROID", WktKeyword.Spheroid, reader);
            case 'T':
                return ReadKeywordSubmatch("OWGS84", WktKeyword.ToWgs84, reader);
            case 'U':
                return ReadKeywordSubmatch("NIT", WktKeyword.Unit, reader);
            case 'V': {
                    if (ReadKeywordSubmatch("ERT_", reader)) {
                        preChar = reader.CurrentUpper;
                        if (reader.MoveNext()) {
                            switch (preChar) {
                            case 'D':
                                return ReadKeywordSubmatch("ATUM", WktKeyword.VerticalDatum, reader);
                            case 'C':
                                return ReadKeywordSubmatch("S", WktKeyword.VerticalCs, reader);
                            }
                        }
                    }
                    break;
                }
            }
            return WktKeyword.None;
        }

        private bool ReadOpenBracket(WktReader reader) {
            if (!reader.SkipWhiteSpace()) {
                return false;
            }
            return reader.IsOpenBracket
                && reader.MoveNext()
            ;
        }

        private bool ReadCloseBracket(WktReader reader) {
            if (!reader.SkipWhiteSpace()) {
                return false;
            }
            bool ok = reader.IsCloseBracket;
            reader.MoveNext();
            return ok;
        }

        private object[] ReadParams(WktReader reader) {
            var paramResults = new List<object>();
            while (true) {
                if (!reader.SkipWhiteSpace()) {
                    return null;
                }
                var paramEntity = ReadEntity(reader);
                if (null == paramEntity) {
                    return null;
                }
                paramResults.Add(paramEntity);
                if (!reader.SkipWhiteSpace()) {
                    return null;
                }
                if (reader.IsComma) {
                    if (!reader.MoveNext()) {
                        return null;
                    }
                }
                else {
                    if (
                        reader.IsCloseBracket
                        && (ReadCloseBracket(reader))
                    ) {
                        break;
                    }
                    return null;
                }
            }
            return paramResults.ToArray();
        }

        private IAuthorityTag ReadAuthorityFromParams(WktReader reader) {
            var names = ReadParams(reader)
                .OfType<string>()
                .ToArray();
            if (names.Length < 2) {
                return null;
            }
            return _authFacs.CreateAuthorityTag(names[0], names[1])
                ?? new OgcAuthorityTag(names[0], names[1]);
        }

        private INamedParameter ReadParameterFromParams(WktReader reader) {
            var all = ReadParams(reader);
            if (all.Length < 2) {
                return null;
            }
            var name = all.OfType<string>().FirstOrDefault();
            var value = all.Skip(1).FirstOrDefault();
            if (null == value || null == name) {
                return null;
            }
            name = name.Replace('_', ' ');
            if (typeof(double) == value.GetType()) {
                return new NamedParameter<double>(name, (double)value);
            }
            return new NamedParameter<object>(name, value);
        }

        private ITransformation ReadParamMtFromParams(WktReader reader) {
            var all = ReadParams(reader);
            var name = all.OfType<string>().FirstOrDefault();
            if(null == name) {
                return null;
            }
            var parms = all.Skip(1).OfType<INamedParameter>();
            return new OgcCoordinateOperationInfo(name, parms);
        }

        private ICoordinateOperationConcatenated ReadConcatMtFromParams(WktReader reader) {
            var all = ReadParams(reader);
            return new CoordinateOperationConcatenated(
                all.OfType<ITransformation>()
            );
        }

        private ITransformation ReadInverseFromParams(WktReader reader) {
            var all = ReadParams(reader).OfType<ITransformation>().ToArray();
            return all.Length == 1
                ? new CoordinateOperationInverse(all.First())
                : null
            ;
        }

        private ITransformation ReadPassthroughFromParams(WktReader reader) {
            var all = ReadParams(reader);
            var index = all
                .Where(o =>
                    null != o
                    && (
                        o.GetType() == typeof(int)
                        || o.GetType() == typeof(double)
                    )
                )
                .Select(Convert.ToInt32)
                .First()
            ;
            return all.Length > 1
                ? new OgcPassthroughOperation(
                    index,
                    all
                        .Skip(1)
                        .OfType<ITransformation>()
                        .FirstOrDefault()
                )
                : null
            ;
        }

        private ISpheroid<double>  ReadSpheroidFromParams(WktReader reader) {
            var all = ReadParams(reader);
            if(all == null || all.Length < 3) {
                return null;
            }
            var name = all[0] as string;
            var majorAxis = Convert.ToDouble(all[1]);
            var invf = Convert.ToDouble(all[2]);
            var auth = all.Length > 3 ? all[3] as IAuthorityTag : null;
            var spheroid = new SpheroidEquatorialInvF(majorAxis,invf);
            return
                (String.IsNullOrEmpty(name) && null == auth)
                ? spheroid
                : (
                    _authFacs.CreateSpheroid(auth)
                    ?? new OgcSpheroid(spheroid, name, auth)
                )
            ;
        }

        private IPrimeMeridian ReadPrimeMFromParams(WktReader reader, IUom angularUnit = null) {
            angularUnit = angularUnit
                ?? _uomGraph.GetUnit("angle", "degree")
            ;
            var all = ReadParams(reader);
            if (all == null || all.Length < 2) {
                return null;
            }
            var name = all[0] as string;
            var lon = Convert.ToDouble(all[1]);
            var auth = all.Length > 2 ? all[2] as IAuthorityTag : null;
            return
                _authFacs.CreatePrimeMeridian(auth)
                ?? new OgcPrimeMeridian(name, lon, angularUnit, auth)
            ;
        }

        private IUom ReadUnitFromParams(WktReader reader, bool isLength = true) {
            var all = ReadParams(reader);
            if (all == null || all.Length < 2) {
                return null;
            }
            var name = all[0] as string;
            var fac = Convert.ToDouble(all[1]);
            var auth = all.Length > 2 ? all[2] as IAuthorityTag : null;
            return
                _authFacs.CreateUom(auth)
                ?? (
                    isLength
                    ? (IUom)new OgcLinearUnit(name,fac,auth)
                    : new OgcAngularUnit(name,fac,auth)
                )
            ;
        }

        private object ReadObject(WktReader reader) {
            WktKeyword keyword = ReadKeyword(reader);
            if (WktKeyword.None == keyword) { return null; }
            if (!ReadOpenBracket(reader)) { return null; }
            switch (keyword) {
            case WktKeyword.Authority:
                return ReadAuthorityFromParams(reader);
            case WktKeyword.Parameter:
                return ReadParameterFromParams(reader);
            case WktKeyword.ParamMt:
                return ReadParamMtFromParams(reader);
            case WktKeyword.ConcatMt:
                return ReadConcatMtFromParams(reader);
            case WktKeyword.InverseMt:
                return ReadInverseFromParams(reader);
            case WktKeyword.PassthroughMt:
                return ReadPassthroughFromParams(reader);
            case WktKeyword.Spheroid:
                return ReadSpheroidFromParams(reader);
            case WktKeyword.PrimeMeridian:
                return ReadPrimeMFromParams(reader);
            case WktKeyword.Unit:
                return ReadUnitFromParams(reader);
            default:
                throw new NotSupportedException("Object type not supported.");
            }
        }

        private object ReadEntity(WktReader reader) {
            if (!reader.SkipWhiteSpace()) {
                return null;
            }
            if (reader.IsValidForDouble) {
                return ReadDouble(reader);
            }
            if (reader.IsDoubleQuote) {
                return ReadQuotedString(reader);
            }
            if (reader.IsKeyword) {
                return ReadObject(reader);
            }
            return null;
        }

        /// <summary>
        /// Parse WKT entities from the <paramref name="reader"/>.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <returns>A WKT entity.</returns>
        public object Parse(TextReader reader) {
            var wktReader = new WktReader(reader, _culture);
            return wktReader.MoveNext() ? ReadEntity(wktReader) : null;
        }

        /// <summary>
        /// Parse WKT entities from the given text string.
        /// </summary>
        /// <param name="wkText">The well known text to parse.</param>
        /// <returns>A WKT entity.</returns>
        public object Parse(string wkText) {
            using (var sr = new StringReader(wkText)) {
                return Parse(sr);
            }
        }

    }
}
